import { useState } from 'react';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { useCart } from '@/contexts/CartContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { cn } from '@/lib/utils';

export default function Payment() {
  const { t } = useLanguage();
  const { items, totalPrice, clearCart } = useCart();
  const navigate = useNavigate();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState('credit_card');
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    zipCode: '',
    country: '',
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // 格式化价格显示
  const formatPrice = (price: number) => {
    return `$${price.toFixed(2)}`;
  };

  // 表单输入变化处理
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误
    if (formErrors[name]) {
      setFormErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 支付方式选择处理
  const handlePaymentMethodChange = (method: string) => {
    setPaymentMethod(method);
  };

  // 表单验证
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};
    
    if (!formData.fullName.trim()) {
      errors.fullName = t('nameRequired');
    }
    
    if (!formData.email.trim()) {
      errors.email = t('emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = t('invalidEmail');
    }
    
    if (!formData.phone.trim()) {
      errors.phone = t('phoneRequired');
    }
    
    if (!formData.address.trim()) {
      errors.address = t('addressRequired');
    }
    
    if (!formData.city.trim()) {
      errors.city = t('cityRequired');
    }
    
    if (!formData.zipCode.trim()) {
      errors.zipCode = t('zipCodeRequired');
    }
    
    if (!formData.country.trim()) {
      errors.country = t('countryRequired');
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 提交订单处理
  const handleSubmitOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 模拟支付处理延迟
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 模拟支付成功
      if (Math.random() > 0.2) { // 80%成功率
        // 清空购物车
        clearCart();
        
        // 显示成功消息
        toast.success(t('paymentSuccess'));
        
        // 跳转到订单确认页面
        navigate('/order-confirmation', { 
          state: { 
            orderId: Math.floor(Math.random() * 1000000),
            total: totalPrice
          } 
        });
      } else {
        // 模拟支付失败
        toast.error(t('paymentFailed'));
      }
    } catch (error) {
      toast.error(t('paymentError'));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-gray-50">
      <Navbar />
      
       <main className="flex-grow py-20">
        <div className="container mx-auto px-4 py-12">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <h1 className="text-3xl font-bold text-gray-900 mb-2">{t('checkout')}</h1>
            <p className="text-gray-600 mb-8">{t('completeOrderPayment')}</p>
          </motion.div>
          
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* 支付表单区域 */}
            <div className="lg:col-span-2 space-y-6">
              {/* 配送信息表单 */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.5, delay: 0.1 }}
                className="bg-white rounded-xl shadow-md p-6 md:p-8"
              >
                <h2 className="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                  <i className="fa-solid fa-truck text-blue-600 mr-2"></i>
                  {t('shippingInformation')}
                </h2>
                
                <form onSubmit={handleSubmitOrder} className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <label htmlFor="fullName" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('fullName')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        id="fullName"
                        name="fullName"
                        value={formData.fullName}
                        onChange={handleInputChange}
                        className={cn(
                          "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                          formErrors.fullName ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                        )}
                      />
                      {formErrors.fullName && (
                        <p className="mt-1 text-sm text-red-500">{formErrors.fullName}</p>
                      )}
                    </div>
                    
                    <div>
                      <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('email')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="email"
                        id="email"
                        name="email"
                        value={formData.email}
                        onChange={handleInputChange}
                        className={cn(
                          "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                          formErrors.email ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                        )}
                      />
                      {formErrors.email && (
                        <p className="mt-1 text-sm text-red-500">{formErrors.email}</p>
                      )}
                    </div>
                  </div>
                  
                  <div>
                    <label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">
                      {t('phone')} <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      value={formData.phone}
                      onChange={handleInputChange}
                      className={cn(
                        "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                        formErrors.phone ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                      )}
                    />
                    {formErrors.phone && (
                      <p className="mt-1 text-sm text-red-500">{formErrors.phone}</p>
                    )}
                  </div>
                  
                  <div>
                    <label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
                      {t('address')} <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="address"
                      name="address"
                      value={formData.address}
                      onChange={handleInputChange}
                      className={cn(
                        "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                        formErrors.address ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                      )}
                    />
                    {formErrors.address && (
                      <p className="mt-1 text-sm text-red-500">{formErrors.address}</p>
                    )}
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div>
                      <label htmlFor="city" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('city')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        id="city"
                        name="city"
                        value={formData.city}
                        onChange={handleInputChange}
                        className={cn(
                          "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                          formErrors.city ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                        )}
                      />
                      {formErrors.city && (
                        <p className="mt-1 text-sm text-red-500">{formErrors.city}</p>
                      )}
                    </div>
                    
                    <div>
                      <label htmlFor="zipCode" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('zipCode')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        id="zipCode"
                        name="zipCode"
                        value={formData.zipCode}
                        onChange={handleInputChange}
                        className={cn(
                          "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                          formErrors.zipCode ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                        )}
                      />
                      {formErrors.zipCode && (
                        <p className="mt-1 text-sm text-red-500">{formErrors.zipCode}</p>
                      )}
                    </div>
                    
                    <div>
                      <label htmlFor="country" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('country')} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        id="country"
                        name="country"
                        value={formData.country}
                        onChange={handleInputChange}
                        className={cn(
                          "w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 transition-colors",
                          formErrors.country ? "border-red-500 focus:border-red-500" : "border-gray-300 focus:border-blue-500"
                        )}
                      />
                      {formErrors.country && (
                        <p className="mt-1 text-sm text-red-500">{formErrors.country}</p>
                      )}
                    </div>
                  </div>
                </form>
              </motion.div>
              
              {/* 支付方式选择 */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.5, delay: 0.2 }}
                className="bg-white rounded-xl shadow-md p-6 md:p-8"
              >
                <h2 className="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                  <i className="fa-solid fa-credit-card text-blue-600 mr-2"></i>
                  {t('paymentMethod')}
                </h2>
                
                <div className="space-y-4">
                  <div 
                    onClick={() => handlePaymentMethodChange('credit_card')}
                    className={cn(
                      "flex items-center p-4 border rounded-lg cursor-pointer transition-all",
                      paymentMethod === 'credit_card' 
                        ? "border-blue-600 bg-blue-50 shadow-sm" 
                        : "border-gray-300 hover:border-gray-400"
                    )}
                  >
                    <div className="w-5 h-5 rounded-full border-2 flex items-center justify-center mr-4">
                      {paymentMethod === 'credit_card' && (
                        <div className="w-3 h-3 rounded-full bg-blue-600"></div>
                      )}
                    </div>
                    <div className="flex items-center">
                      <i className="fa-solid fa-credit-card text-xl text-gray-600 mr-3"></i>
                      <span className="font-medium">{t('creditCard')}</span>
                    </div>
                  </div>
                  
                  <div 
                    onClick={() => handlePaymentMethodChange('paypal')}
                    className={cn(
                      "flex items-center p-4 border rounded-lg cursor-pointer transition-all",
                      paymentMethod === 'paypal' 
                        ? "border-blue-600 bg-blue-50 shadow-sm" 
                        : "border-gray-300 hover:border-gray-400"
                    )}
                  >
                    <div className="w-5 h-5 rounded-full border-2 flex items-center justify-center mr-4">
                      {paymentMethod === 'paypal' && (
                        <div className="w-3 h-3 rounded-full bg-blue-600"></div>
                      )}
                    </div>
                    <div className="flex items-center">
                      <i className="fa-brands fa-paypal text-xl text-blue-600 mr-3"></i>
                      <span className="font-medium">PayPal</span>
                    </div>
                  </div>
                  
                  <div 
                    onClick={() => handlePaymentMethodChange('bank_transfer')}
                    className={cn(
                      "flex items-center p-4 border rounded-lg cursor-pointer transition-all",
                      paymentMethod === 'bank_transfer' 
                        ? "border-blue-600 bg-blue-50 shadow-sm" 
                        : "border-gray-300 hover:border-gray-400"
                    )}
                  >
                    <div className="w-5 h-5 rounded-full border-2 flex items-center justify-center mr-4">
                      {paymentMethod === 'bank_transfer' && (
                        <div className="w-3 h-3 rounded-full bg-blue-600"></div>
                      )}
                    </div>
                    <div className="flex items-center">
                      <i className="fa-solid fa-university text-xl text-gray-600 mr-3"></i>
                      <span className="font-medium">{t('bankTransfer')}</span>
                    </div>
                  </div>
                </div>
                
                {/* 信用卡表单 (仅在选择信用卡时显示) */}
                {paymentMethod === 'credit_card' && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    transition={{ duration: 0.3 }}
                    className="mt-6 pt-6 border-t border-gray-200 space-y-6"
                  >
                    <div>
                      <label htmlFor="cardNumber" className="block text-sm font-medium text-gray-700 mb-1">
                        {t('cardNumber')}
                      </label>
                      <input
                        type="text"
                        id="cardNumber"
                        placeholder="1234 5678 9012 3456"
                        className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      />
                    </div>
                    
                    <div className="grid grid-cols-2 gap-6">
                      <div>
                        <label htmlFor="expiryDate" className="block text-sm font-medium text-gray-700 mb-1">
                          {t('expiryDate')}
                        </label>
                        <input
                          type="text"
                          id="expiryDate"
                          placeholder="MM/YY"
                          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                        />
                      </div>
                      
                      <div>
                        <label htmlFor="cvv" className="block text-sm font-medium text-gray-700 mb-1">
                          {t('cvv')}
                        </label>
                        <input
                          type="text"
                          id="cvv"
                          placeholder="123"
                          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                        />
                      </div>
                    </div>
                  </motion.div>
                )}
                
                {/* 提交订单按钮 */}
                <div className="mt-8 flex justify-end">
                  <button
                    onClick={handleSubmitOrder}
                    disabled={isSubmitting}
                    className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-8 rounded-lg transition-all transform hover:scale-105 shadow-lg hover:shadow-xl flex items-center"
                  >
                    {isSubmitting ? (
                      <>
                        <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                        {t('processing')}
                      </>
                    ) : (
                      <>
                        {t('placeOrder')}
                        <i className="fa-solid fa-arrow-right ml-2"></i>
                      </>
                    )}
                  </button>
                </div>
              </motion.div>
            </div>
            
            {/* 订单摘要 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="lg:col-span-1"
            >
              <div className="bg-white rounded-xl shadow-md sticky top-24 overflow-hidden">
                <div className="p-6 border-b">
                  <h2 className="text-xl font-bold text-gray-900">{t('orderSummary')}</h2>
                </div>
                
                <div className="p-6 max-h-[400px] overflow-y-auto">
                  {items.map((item, index) => (
                    <div key={item.id} className="flex py-4 border-b last:border-0">
                      <div className="w-16 h-16 rounded-lg overflow-hidden flex-shrink-0">
                        <img 
                          src={item.image} 
                          alt={t(item.nameKey)}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="ml-4 flex-grow">
                        <h3 className="text-sm font-medium text-gray-800 line-clamp-1">{t(item.nameKey)}</h3>
                        <div className="flex justify-between items-center mt-1">
                          <span className="text-sm text-gray-500">{t('quantity')}: {item.quantity}</span>
                          <span className="text-sm font-semibold text-gray-900">
                            {formatPrice(item.price * item.quantity)}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                
                <div className="p-6 border-t">
                  <div className="flex justify-between py-2">
                    <span className="text-gray-600">{t('subtotal')}</span>
                    <span className="font-medium">{formatPrice(totalPrice)}</span>
                  </div>
                  <div className="flex justify-between py-2">
                    <span className="text-gray-600">{t('shipping')}</span>
                    <span className="font-medium text-green-600">{t('free')}</span>
                  </div>
                  <div className="flex justify-between py-2">
                    <span className="text-gray-600">{t('tax')}</span>
                    <span className="font-medium">{formatPrice(totalPrice * 0.1)}</span>
                  </div>
                  <div className="flex justify-between py-4 mt-2 border-t">
                    <span className="font-bold text-lg">{t('total')}</span>
                    <span className="font-bold text-lg text-blue-800">
                      {formatPrice(totalPrice * 1.1)}
                    </span>
                  </div>
                  
                  {/* 安全支付信息 */}
                  <div className="mt-8 pt-6 border-t border-gray-200">
                    <div className="flex items-center text-green-600 mb-4">
                      <i className="fa-solid fa-shield text-xl mr-2"></i>
                      <span className="font-medium">{t('securePayment')}</span>
                    </div>
                    <p className="text-sm text-gray-500 mb-4">{t('paymentGuarantee')}</p>
                    <div className="flex flex-wrap gap-2">
                      <i className="fa-brands fa-cc-visa text-xl text-gray-600"></i>
                      <i className="fa-brands fa-cc-mastercard text-xl text-gray-600"></i>
                      <i className="fa-brands fa-cc-amex text-xl text-gray-600"></i>
                      <i className="fa-brands fa-cc-paypal text-xl text-gray-600"></i>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        </div>
      </main>
      
      <Footer />
    </div>
  );
}